package com.mnt.washio.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mnt.washio.R;
import com.mnt.washio.objects.OrderObject;
import com.mnt.washio.utils.network.WebServiceCommunicatorListener;
import com.mnt.washio.utils.network.ws.BaseWSControl;
import com.mnt.washio.utils.network.ws.BaseWSControl.WebServiceFlag;
import com.mnt.washio.utils.network.ws.GetCurrentOrderWSControl;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.parse.ParseUser;

@SuppressLint("SimpleDateFormat")
public class OrderStatusActivity extends BaseActivity implements
		WebServiceCommunicatorListener {
	private TextView myTvStatus, myTvTime1, myTvDate1, myTvTime2, myTvDate2;
	private ImageView myImg1, myImg2, myImgStatus;
	private ProgressDialog pd;
	private Timer myTimer;
	private OrderObject mOrderObject;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_status);
		initView();
		initProperties();
		initListeners();

		myTimer = new Timer();
		myTimer.schedule(new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				new GetCurrentOrderWSControl(OrderStatusActivity.this,
						OrderStatusActivity.this, ParseUser.getCurrentUser()
								.getObjectId()).execute();
			}
		}, 0, 60000); // 1 min.

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		myTimer.cancel();
		myTimer.purge();
		super.onDestroy();
	}

	public void initProperties() {
		DisplayImageOptions options = new DisplayImageOptions.Builder()
				.resetViewBeforeLoading().cacheOnDisc().cacheInMemory()
				.cacheOnDisc()
				.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
				.bitmapConfig(Bitmap.Config.ARGB_8888)
				.showStubImage(R.drawable.placeholder_ninja)
				.showImageOnFail(R.drawable.placeholder_ninja)
				.showImageForEmptyUri(R.drawable.placeholder_ninja)
				.displayer(new SimpleBitmapDisplayer()).build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				getApplicationContext())
				.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 768))
				.memoryCacheSize(2 * 1024 * 1024)
				.imageDownloader(
						new BaseImageDownloader(getApplicationContext())) // default
				.tasksProcessingOrder(QueueProcessingType.FIFO) // default
				.defaultDisplayImageOptions(options) // default
				.enableLogging().build();
		ImageLoader.getInstance().init(config);

		pd = new ProgressDialog(OrderStatusActivity.this);
		pd.setMessage("Loading...");
		pd.setCancelable(false);

		mOrderObject = (OrderObject) getIntent().getSerializableExtra(
				"ORDER_OBJECT");
		if (mOrderObject == null) {
			new GetCurrentOrderWSControl(this, this, ParseUser.getCurrentUser().getObjectId()).execute();
		} else {
			checkOrder();
		}
	}

	@Override
	protected void initView() {
		super.initView();
		((TextView) findViewById(R.id.tv_title_bar)).setText("Order Status");
		myTvTime1 = (TextView) findViewById(R.id.tv_time);
		myTvTime2 = (TextView) findViewById(R.id.tv_time_1);
		myTvDate1 = (TextView) findViewById(R.id.tv_date);
		myTvDate2 = (TextView) findViewById(R.id.tv_date_1);
		myTvStatus = (TextView) findViewById(R.id.tv_status);
		myImg1 = (ImageView) findViewById(R.id.img_avatar);
		myImg2 = (ImageView) findViewById(R.id.img_avatar1);
		myImgStatus = (ImageView) findViewById(R.id.imgStaus);

	}

	private void initListeners() {
		((ImageView) findViewById(R.id.imv_menu))
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						finish();
					}
				});
	}

	@Override
	public void onConnectionOpen(BaseWSControl wsControl, WebServiceFlag flag) {
		// TODO Auto-generated method stub

		try {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if(null != pd)
						pd.show();
				}
			});

		} catch (Exception e) {
		}

	}

	@Override
	public void onConnectionError(BaseWSControl wsControl, WebServiceFlag flag,
			String error) {
		// TODO Auto-generated method stub
		try {
			Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
			pd.dismiss();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@SuppressLint("SimpleDateFormat")
	@Override
	public void onConnectionDone(BaseWSControl wsControl, WebServiceFlag flag,
			Object result) {
		// TODO Auto-generated method stub

		try {
			pd.dismiss();
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (null == result)
			return;
		mOrderObject = (OrderObject) result;
		checkOrder();

	}

	@Override
	public void onUpdateData(BaseWSControl wsControl, WebServiceFlag flag,
			Object data) {
		// TODO Auto-generated method stub

	}

	public void checkOrder() {

		if (!mOrderObject.getRating().equals("null")
				|| mOrderObject.getStatusLookup().equals("ORDER_CANCELLED")) {
			startActivity(new Intent(this, OrderActivity.class));
			myTimer.purge();
			finish();
			return;
		}

		if (mOrderObject.getStatusLookup().equals("ORDER_DELIVERED")
				|| mOrderObject.getStatusLookup().equals("CUSTOMER_REFUNDED")
				|| mOrderObject.getStatusLookup().equals("CUSTOMER_BILLED")) {
			
			Intent i = new Intent(this, OrderComplete.class);
			i.putExtra("ORDER_OBJECT", mOrderObject);
			startActivity(i);
			myTimer.purge();
			finish();
			return;
		}
		reloadOrder(mOrderObject);

	}

	public void reloadOrder(OrderObject order) {
		int progress = order.getOrdinalValueClient() - 1;
		if (progress < 0)
			progress = 0;
		if (progress > 4)
			progress = 4;

		int resId = getResources().getIdentifier("wheel_progress_" + progress,
				"drawable", getPackageName());
		myImgStatus.setImageDrawable(getResources().getDrawable(resId));
		String date = order.getPickupDate();

		String date1 = order.getDropoffDate();
		String pattern = "yyyy-MM-dd'T'HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		Date d = null, d1 = null;
		try {
			d = sdf.parse(date);
			d1 = sdf.parse(date1);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		myTvDate1.setText(new SimpleDateFormat("EEE M/d").format(d));
		myTvDate2.setText(new SimpleDateFormat("EEE M/d").format(d1));
		myTvTime1.setText(order.getPickupTime() + " - "
				+ getTime(order.getPickupTime()));
		myTvTime2.setText(order.getDropoffTime() + " - "
				+ getTime(order.getDropoffTime()));
		myTvStatus.setText(order.getStatusClient());

		ImageLoader.getInstance().loadImage(order.getUrlImgPick().trim(),
				new ImageLoadingListener() {

					@Override
					public void onLoadingStarted(String imageUri, View view) {
					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						// TODO Auto-generated method stub
						myImg1.setImageBitmap(loadedImage);
					}

					@Override
					public void onLoadingCancelled(String imageUri, View view) {
						// TODO Auto-generated method stub

					}
				});

		ImageLoader.getInstance().loadImage(order.getUrlImgDrop().trim(),
				new ImageLoadingListener() {

					@Override
					public void onLoadingStarted(String imageUri, View view) {
					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						// TODO Auto-generated method stub
						myImg2.setImageBitmap(loadedImage);
					}

					@Override
					public void onLoadingCancelled(String imageUri, View view) {
						// TODO Auto-generated method stub

					}
				});
	}

	public String getTime(String time) {
		String[] str = time.split(":");
		int num1 = Integer.parseInt(str[0]);
		int num2 = Integer.parseInt(str[1]);
		num2 = num2 + 30;
		if (num2 >= 60) {
			num2 = 0;
			num1 += 1;
		}
		return (num1 < 10 ? ("0" + num1) : (num1 + "")) + ":"
				+ (num2 < 10 ? ("0" + num2) : (num2 + ""))
				+ (num1 >= 12 ? "PM" : "AM");
	}

}
